_comp_sievemgr() {
	local cmd="$1" word="$2" pre="$3"

	set -- $COMP_LINE
	shift

	local argdel=0
	while [ $# -gt 0 ]
	do
		case $1 in
		(--)		shift
				break
				;;
		(-*[co])	local optopt="${1: -1}"
				local optarg="${1#-*$optopt}"
				if [ "$optarg" ]
				then
					shift
				elif
					[ $# -gt 1 ]
				then
					shift 2
				else
					shift
					argdel=1
				fi
				;;
		(-*)		local optopt="${1#-}"
				shift ;;
		(*)		break
		esac
	done

	case $COMP_LINE in
	(*" ")	local argidx=$(($# - argdel + 1)) ;;
	(*)	local argidx=$(($# - argdel)) ;;
	esac

	local replies
	case $argidx in
	(0)	case $word in
		(--)		COMPREPLY=()
				return
				;;
		(-)		COMPREPLY=(-N -V -c -d -f -h -o -q -v)
				return
				;;
		(-*[co])	:
				;;
		(-*)		COMPREPLY=("$word")
				return
				;;
		esac

		case $optopt in
		(o)	replies=(
				'alias='
				'authmechs='
				'backup=none'
				'backup=simple'
				'backup=numbered'
				'cafile='
				'cadir='
				'cert='
				'confdir='
				'confirm='
				'debugauth=no'
				'debugauth=sasl'
				'debugauth=sieve'
				'getkeypass='
				'getpass='
				'host='
				'key='
				'login='
				'port='
				'tls=no'
				'tls=yes'
				'saslprep=usernames'
				'saslprep=passwords'
				'saslprep=all'
				'saslprep=none'
				'stacktrace=no'
				'stacktrace=yes'
				'verbosity=debug'
				'verbosity=error'
				'verbosity=info'
				'verbosity=warning',
				'x509strict=no',
				'x509strict=yes',
			)
			;;
		(*)	COMPREPLY=("$word")
			return
		esac
		;;
	(1)	local home="${HOME-}"
		[ "$home" ] && eval home=~
		local xdg_data_home="${XDG_DATA_HOME:-"$home/.config"}"

		local rc
		for rc in				\
			"$xdg_data_home/sieve/sieverc"	\
			"$home/.sieve/sieverc"		\
			"$home/.sieverc"		\
			"/etc/sieve/sieverc"		\
			"/etc/sieverc"
		do
			[ -e "$rc" ] && break
		done

		local key value
		while read -r key value
		do
			case $key in
			(account|alias)	: ;;
			(*)		continue
			esac

			case $word in
			(*@*)	local netloc="${word##*@}"
				case $value in
				("$netloc"*) COMPREPLY+=("${2%@*}@$value")
				esac
				;;
			(*)	case $value in
				("$word"*) COMPREPLY+=("$value")
				esac
				;;
			esac
		done <"$rc"

		return
		;;
	(2)	local replies=(
			'activate'
			'caps'
			'cat'
			'cd'
			'cert'
			'check'
			'cp'
			'deactivate'
			'diff'
			'ed'
			'exit'
			'get'
			'help'
			'ls'
			'mget'
			'more'
			'mput'
			'mv'
			'put'
			'python'
			'rm'
			'sh'
			'su'
			'vi'
		)
		;;
	esac

	local reply
	for reply in "${replies[@]}"
	do
		case $reply in
		("$word"*) COMPREPLY+=("$reply")
		esac
	done

	if	[ "$optopt" = o ]		&&
		[ "${#COMPREPLY[@]}" -eq 1 ]	&&
		[ "${COMPREPLY[0]: -1}" = '=' ]
	then
		compopt -o nospace
	fi
} && complete -F _comp_sievemgr -o default sievemgr
